package com.wl.dzt.sys.controller.action;

import java.util.HashSet;
import java.util.Map;

import com.wl.dzt.sys.controller.param.Param;
import com.wl.dzt.sys.controller.result.ActionResult;
import com.wl.dzt.sys.core.dao.DB;
import com.wl.dzt.sys.core.dao.select.Select;
import com.wl.dzt.sys.core.dao.select.term.Term;
import com.wl.dzt.sys.util.FieldUtil;
import com.wl.dzt.sys.util.clazz.ClassUtil;
import com.wl.dzt.sys.util.json.Json;
import org.springframework.stereotype.Component;


/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description 加载动作
 * 用于执行加载请求
 * 根据参数执行加载动作
 * 支持级联加载
 */
@Component
public class LoadAction implements Action {

    public ActionResult doAction(Param param) {
        ActionResult actionResult = new ActionResult();
        Map<String, Object> data = DB.getByMap(param.getClazz(), param.getId(), param.getFields());
        actionResult.setEntity(data);
        param.setEntity(data);
        if (data != null) {
            caseEntitysSet(param);
        }
        return actionResult;
    }

    /**
     * <b>加载时级联出set</b>
     * <p>
     * 根据页面参数和实体设置,加载时同时加载出当前set中的值
     * </p>
     *
     * @param param
     */
    private void caseEntitysSet(Param param) {
        Map<String, Object> entity = (Map<String, Object>) param.getEntity();
        String id = entity.get("id") + "";
        FieldUtil.getEntitySet(ClassUtil.newInstance(param.getClazz())).forEach(
                info -> {
                    if (info.isAutoLoad()) {
                        entity.put(
                                info.getSrcField(),
                                Json.parse(new HashSet<>(DB.list(Select.create(info.getSrcClass()).fields(info.getFields())
                                        .where(Term.eq(info.getRefField() + ".id", id))))));
                    }
                });
    }

}
